import json
from flask import jsonify
import logging
from datetime import datetime

def success_response(data=None, message='操作成功', code=200):
    """成功响应格式化"""
    return jsonify({
        'code': code,
        'message': message,
        'data': data
    })

def error_response(message='操作失败', code=500):
    """错误响应格式化"""
    return jsonify({
        'code': code,
        'message': message,
        'data': None
    })

def parse_json_data(json_str):
    """解析JSON数据"""
    if not json_str:
        return None
    try:
        return json.loads(json_str)
    except json.JSONDecodeError:
        return None

def format_json_data(data):
    """格式化JSON数据"""
    if not data:
        return None
    try:
        return json.dumps(data, ensure_ascii=False)
    except (TypeError, ValueError):
        return None

def validate_json_data(data):
    """验证JSON数据"""
    if not data:
        return False
    try:
        json.dumps(data)
        return True
    except (TypeError, ValueError):
        return False

def log_info(app, module, message, user=None):
    """记录信息日志"""
    try:
        from .services import LogService
        LogService.add_log('INFO', module, message, user)
    except Exception as e:
        app.logger.error(f'记录日志失败: {str(e)}')

def log_error(app, module, message, user=None):
    """记录错误日志"""
    try:
        from .services import LogService
        LogService.add_log('ERROR', module, message, user)
    except Exception as e:
        app.logger.error(f'记录日志失败: {str(e)}')

def log_warning(app, module, message, user=None):
    """记录警告日志"""
    try:
        from .services import LogService
        LogService.add_log('WARNING', module, message, user)
    except Exception as e:
        app.logger.error(f'记录日志失败: {str(e)}')